#include "Comm.hpp"
#include "Log.hpp"
using namespace std;

// 充当创建内存的角色

// 创建全新的共享内存
const int flags = IPC_CREAT | IPC_EXCL;
int main()
{
    key_t key = CreateKey();
    Log() << "key(hex): 0x" << hex << key << endl;
    Log() << "Begin create share memory!\n";
    int shmid = shmget(key, MEM_SIZE, flags | 0666); //"| 0666"权限控制
    if (shmid < 0)
    {
        Log() << "shmget: " << strerror(errno) << "\n";
        return 2;
    }
    //sleep(3);
    Log() << "Create shm success! shmid: " << shmid << "\n";
    // 使用
    // 1.将共享内存和自己的进程产生关联attach
    char *str = (char *)shmat(shmid, nullptr, 0);
    Log() << "Attach shm: " << shmid << " success！\n";
    //sleep(3);

    //测试共享内存通信
    while(true)
    {
        printf(".%s\n",str);
        sleep(1);
    }

    // 2.去关联
    shmdt(str);
    Log() << "Dttach shm: " << shmid << " success！\n";
    //sleep(3);

    // 删除
    shmctl(shmid, IPC_RMID, nullptr);
    Log() << "Delete shm,shmid: " << shmid << " success!\n";

    // sleep(3);
    return 0;
}
